package com.corgi.test.java8.map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title: NewMap
 * @description: java8 map.merge()
 * @author: dengmiao
 * @create: 2019-10-13 19:45
 **/
public class NewMapMerge {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws JsonProcessingException {
        Map<String, Integer> studentScoreMap = new HashMap<>(16);
        List<StudentScore> studentScoreList = buildScoreList();

        oldAchieve(studentScoreList);

        // 分组求和
        studentScoreList.forEach(studentScore -> studentScoreMap.merge(
                studentScore.getName(),
                studentScore.getScore(),
                Integer::sum));

        System.out.println(objectMapper.writeValueAsString(studentScoreMap));
    }

    private static void oldAchieve(List<StudentScore> studentScoreList) throws JsonProcessingException {
        Map<String, Integer> studentScoreMap = new HashMap<>(16);
        studentScoreList.forEach(studentScore -> {
            if (studentScoreMap.containsKey(studentScore.getName())) {
                studentScoreMap.put(studentScore.getName(),
                        studentScoreMap.get(studentScore.getName()) + studentScore.getScore());
            } else {
                studentScoreMap.put(studentScore.getName(), studentScore.getScore());
            }
        });
        System.out.println(objectMapper.writeValueAsString(studentScoreMap));
    }

    public static List buildScoreList() {
        List list = Lists.newArrayList(
                new StudentScore().setName("张三").setSubject("语文").setScore(70),
                new StudentScore().setName("张三").setSubject("数学").setScore(80),
                new StudentScore().setName("张三").setSubject("英语").setScore(65),
                new StudentScore().setName("李四").setSubject("语文").setScore(68),
                new StudentScore().setName("李四").setSubject("数学").setScore(70),
                new StudentScore().setName("李四").setSubject("英语").setScore(90),
                new StudentScore().setName("王五").setSubject("语文").setScore(80),
                new StudentScore().setName("王五").setSubject("数学").setScore(85),
                new StudentScore().setName("王五").setSubject("英语").setScore(70)
        );
        return list;
    }

    @Data
    @Accessors(chain = true)
    public static class StudentScore {

        private String name;

        private String subject;

        private Integer score;
    }
}
